package com.leung.handler;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.leung.domain.entity.TbLamp;
import com.leung.service.ITbLampService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理入站消息
 */
@Slf4j
@Component(value = "receiverMessageHandler")
public class ReceiverMessageHandler implements MessageHandler {

    @Autowired
    private ITbLampService tbLampService;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        MessageHeaders headers = message.getHeaders();
        log.debug("message:{}",message);
        String receivedTopicName = (String) headers.get("mqtt_receivedTopic");
        if("atguigu/iot/lamp/line".equals(receivedTopicName)) {
            String tbLambStr = message.getPayload().toString();
            TbLamp tbLamp = JSON.parseObject(tbLambStr, TbLamp.class);
            LambdaUpdateWrapper<TbLamp> updateWrapper = new LambdaUpdateWrapper<TbLamp>()
                    .eq(TbLamp::getDeviceId, tbLamp.getDeviceId())
                    .set(TbLamp::getStatus, tbLamp.getStatus())
                    .set(TbLamp::getUpdateTime, new Date());
            boolean update = tbLampService.update(updateWrapper);
            if (update) {
                log.info("更新成功:{}", tbLamp);
            } else {
                log.info("更新失败:{}", tbLamp);
            }
        }
    }

}